import Vue from 'vue'
import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'

let isHttpRequestStatus = true

const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
	timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
	  if (config.method === 'get') {
		  if (config.params) {
			  config.params['t'] = new Date().getTime()
		  } else {
			  config['params'] = { t: new Date().getTime() }
		  }
	  }
	  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
	  config.headers['Accept'] = 'application/json'
	  // config.headers['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjZiNjAxYjc4LTMxY2EtNDU2My05MWE2LTE1N2I3NGE3YTczNSJ9.7slCeTgBB92-luFGwptJCuD4UsDixCjQwVJaL2bygUXcToMZq1dyOkaDPohiKnmpeXfa1JxN4KH1o_PxiZUPvQ'
	  config.headers['token'] = Cookies.get('token')
	  return config
  },
  error => {
	  console.log(error) // for debug
	  Promise.reject(error)
  }
)

// 请求返回
service.interceptors.response.use(
  response => {
	  let res = response.data
	  if (res.code === 401) {
		  Vue.prototype.$confirm('登录状态已过期，您是否重新登录?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  type: 'warning'
		  }).then(() => {
			  Cookies.remove('token')
			  router.push({ path: '/login' })
			  Vue.prototype.$message.success('退出成功，请重新登录！')
		  }).catch(() => {
		  })
		  return false
	  }
	  if (res.code === 0) {
		  return res
	  } else {
		  if (isHttpRequestStatus) {
			  Vue.prototype.$message.error(res.msg)
			  isHttpRequestStatus = false
			  setTimeout(() => {
				  isHttpRequestStatus = true
			  }, 2000)
		  }
		  return { err: res }
	  }
  },
  error => {
	  if (error.response.data.code) { }
	  console.log('err' + error) // for debug
	  return { err: error.response }
  }
)
export default service
